package com.android.kmlmrg.services.rest.method;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.apache.http.HttpStatus;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Application;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.android.kmlmrg.R;
import com.android.kmlmrg.event.RestAddUserEvent;
import com.android.kmlmrg.event.RestGetUserEvent;
import com.android.kmlmrg.event.UserDelEvent;
import com.android.kmlmrg.listener.custom.RestAddUserListener;
import com.android.kmlmrg.listener.custom.RestGetUserListener;
import com.android.kmlmrg.listener.custom.RestReportListener;
import com.android.kmlmrg.listener.custom.RestUserDelListener;
import com.android.kmlmrg.listener.custom.UsersListener;
import com.android.kmlmrg.model.ApiSession;
import com.android.kmlmrg.model.User;
import com.android.kmlmrg.services.ServiceController;

/**
 * 
 * @author mayki
 *
 */
public class DeleteUser extends AsyncTask<Void, Integer, String> {


	/**LOG**/
	private static final  String LOG_TAG = DeleteUser.class.getSimpleName();
	
	private User vUser;
	
	private static final String METHODE_NAME = "/delete";
	
	private Application application;
	
	private static  ArrayList<RestUserDelListener> listeners = new ArrayList<RestUserDelListener>();
	
	private int code;
	
	public DeleteUser(Application pApplication, User user) {
		Log.i(LOG_TAG, "START - CONSTRUCTEUR DeleteUser ");	
		application = pApplication;	
		vUser = user;

		Log.i(LOG_TAG, "END - CONSTRUCTEUR DeleteUser ");
	}

	
	protected String doInBackground(Void... sUrl) {
		try {
			String vUrl = this.application.getString(R.string.user_endpoint) + METHODE_NAME + "/" + vUser.getIdentifiant();

			ApiSession vApiSession =  ServiceController.getInstance().getApiSession() ;
			JSONObject vJsonObject = new JSONObject();				
			vJsonObject.put(ApiSession.WSCALLERID, vApiSession.getWsCallerId());
			vJsonObject.put(ApiSession.TIMESTAMP, vApiSession.getTimesTamp());
			vJsonObject.put(ApiSession.HASH, vApiSession.getHash());
			String message = vJsonObject.toString();

			URLConnection url = new URL(vUrl).openConnection();
			HttpURLConnection httpcon = (HttpURLConnection) ((new URL(vUrl).openConnection()));

			httpcon.setRequestProperty("Content-Type", "application/json");
			httpcon.setRequestProperty("Accept", "application/json");
			httpcon.setRequestMethod("POST");

			httpcon.setDoInput(true);
			httpcon.setDoOutput(true);
			httpcon.setFixedLengthStreamingMode(message.getBytes().length);
			httpcon.connect();


			OutputStream os = new BufferedOutputStream(httpcon.getOutputStream());
			os.write(message.getBytes());
			//clean up
			os.flush();


			// this will be useful so that you can show a typical 0-100% progress bar
			int fileLength = httpcon.getContentLength();
			
			 code = httpcon.getResponseCode();

			// download the file

			InputStream input = httpcon.getInputStream();
			BufferedReader r = new BufferedReader(new InputStreamReader(input));
			StringBuilder total = new StringBuilder();
			String line;
			while ((line = r.readLine()) != null) {
				total.append(line);
			}
			os.flush();
			os.close();
			input.close();	

			return total.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	
	public static void addListener ( RestUserDelListener pListener ){
		listeners.add(pListener);
	}

	public static void removeListener( RestUserDelListener pListener ){
		listeners.remove(pListener);
	}

	public static void fireDelUser( UserDelEvent pUserAddEvent ){		
		for(RestUserDelListener listener : listeners){
			listener.resultUserDelRequest( pUserAddEvent );
		}
	}

	
	@Override
	protected void onPostExecute(String result) {
		Log.i(LOG_TAG, "START - handleJson (int pStatusCode, String in) ");
		Log.i(LOG_TAG, "RESULT : " + result);
		Log.i(LOG_TAG, "StatusCode : " + code);
		
		Log.i(LOG_TAG, "END - handleJson (int pStatusCode, String in) ");
		if (!result.contains("\"errorCode\": \"200\"")) {	
			UserDelEvent vEvent = new UserDelEvent(this, vUser);
			fireEvent(vEvent);
		}else{
			   Toast.makeText(application.getApplicationContext(), "Impossible de supprimer cet utilisateur ", Toast.LENGTH_SHORT).show();
		}
		Log.i(LOG_TAG, "END - onPostExecute");
		super.onPostExecute(result);
	}

	
	private void fireEvent( UserDelEvent pEvent ){		
		for(RestUserDelListener listener : listeners){
			listener.resultUserDelRequest( pEvent );
		}
	}

}
